package org.lw.advice;

import org.lw.response.ApiResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import java.util.NoSuchElementException;
/*
*   全局异常处理类: 用于处理所有Controller中抛出的异常
* */
@ControllerAdvice
public class GlobalExceptionHandler {


    // 处理找不到资源的异常
    @ExceptionHandler(NoSuchElementException.class)
    public ResponseEntity<ApiResponse<String>> handleNoSuchElementException(NoSuchElementException ex) {
        return ResponseEntity
                .status(404) // 404 Not Found
                .body(new ApiResponse<>(404, ex.getMessage(), null));
    }

    // 处理所有其他未处理的异常
    @ExceptionHandler(Exception.class)
    public ResponseEntity<ApiResponse<String>> handleException(Exception ex) {
        return ResponseEntity
                .status(500) // 500 Internal Server Error
                .body(new ApiResponse<>(500, "Internal Server Error", ex.getMessage()));
    }
}

